const { excuSQL } = require('../../db')
const { getHaveData, getCode, updataData, addData } = require('../../code/utils')

const express = require('express')
const userRouter = express.Router()


userRouter.get('/get', (req, res) => {
    let sql = `select * from user`
    return excuSQL(sql).then((data) => {
        res.send(getCode(data, '成功'))
    }).catch(() => {
        res.send(getCode(data, '失败', 1001))
    })
})

// 列表
userRouter.post('/getUserList', (req, res) => {
    let { firstNum, num, score, age, name } = req.body
    let formData = { score, age, name }
    let sql = `select * from user ${getHaveData(formData)} limit ${firstNum ? firstNum : 0},${num ? num : 10}`
    return excuSQL(sql).then((data) => {
        let sql2 = `select count(*) from user ${getHaveData(formData)}`
        excuSQL(sql2).then((total) => {
            res.send(getCode({
                list: data,
                total: total[0]['count(*)'],
                count: data.length
            }, '成功'))
        }).catch((err) => {
            res.send(getCode(err, '失败', 3001))
        })
    }).catch((err) => {
        res.send(getCode(err, '失败', 3001))
    })
})

// 按id查询
userRouter.post('/getUserInfo', (req, res) => {
    let { id } = req.body
    if (!id) {
        res.send(getCode({}, '未填写id', 3001))
    } else {
        let sql = `select * from user ${getHaveData({ id })}`
        return excuSQL(sql).then((data) => {
            res.send(getCode(data[0] ? data[0] : {}, '成功'))
        }).catch((err) => {
            res.send(getCode(err, '错误', 3001))
            throw err
        })
    }
})

// 增加
userRouter.post('/addUser', (req, res) => {
    let { score, age, name } = req.body
    let formData = { score, age, name }
    let test = `INSERT into user (name,score,age) VALUES ('小王','M',81)`
    let sql = `insert into user ${addData(formData)}`
    return excuSQL(sql).then((data) => {
        res.send(getCode(formData, '添加成功'))
    }).catch((err) => {
        res.send(getCode(err, '错误', 3001))
        throw err
    })
})

// 删除
userRouter.post('/delUser', (req, res) => {
    let { id } = req.body
    let sql = `delete from user ${getHaveData({ id })}`
    return excuSQL(sql).then(() => {
        res.send(getCode({}, '删除成功'))
    }).catch((err) => {
        res.send(getCode(err, '错误', 3001))
        throw err
    })
})

// 修改
userRouter.post('/updateUser', (req, res) => {
    let { score, age, id, name } = req.body
    let formData = { score, age, name }
    if (!id) {
        res.send(getCode({}, '未填写id', 3001))
    } else {
        let sql = `update user set ${updataData(formData)} ${getHaveData({ id })}`
        return excuSQL(sql).then(() => {
            res.send(getCode(formData, '修改成功'))
        }).catch((err) => {
            res.send(getCode(err, '错误', 3001))
            throw err
        })
    }
})
module.exports = userRouter